package com.github.sd4324530.fastweixin.api.extra;

import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.response.GetJsApiTicketResponse;
import com.github.sd4324530.fastweixin.api.response.GetTokenResponse;
import com.github.sd4324530.fastweixin.exception.WeixinException;
import com.github.sd4324530.fastweixin.util.JSONUtil;
import com.github.sd4324530.fastweixin.util.NetWorkCenter;
import com.github.sd4324530.fastweixin.util.StrUtil;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * token 刷新方法
 */
public class TokenService {
    private static final Logger LOG = LoggerFactory.getLogger(TokenService.class);


    static void initTokenAndTicket(ApiConfig config,TokenCache cache){
        Token token = getToken(config);
        Token ticket = getJSToken(token);

        cache.put(token);
        cache.put(ticket);
    }

    /**
     * 获取access_token
     */
    static Token getToken(ApiConfig config) {
        long now = System.currentTimeMillis();
        LOG.debug("开始获取access_token........");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.getAppid() + "&secret=" + config.getSecret();
        final Token token = new Token();
        NetWorkCenter.get(url, null, new NetWorkCenter.ResponseCallback() {
            @Override
            public void onResponse(int resultCode, String resultJson) {
                if (HttpStatus.SC_OK == resultCode) {
                    GetTokenResponse response = JSONUtil.toBean(resultJson, GetTokenResponse.class);
                    LOG.debug("获取access_token:{}", response.getAccessToken());
                    if (null == response.getAccessToken()) {
                        throw new WeixinException("微信公众号token获取出错，错误信息:" + response.getErrcode() + "," + response.getErrmsg());
                    }
                    token.setToken(response.getAccessToken());
                }
            }
        });
        token.setAppid(config.getAppid());
        token.setType(TokenType.ACCESS_TOKEN);
        token.setUpdateTime(now);
        return token;
    }

    /**
     * 获取JS-SDK token
     */
    static Token getJSToken(Token accessToken) {
        long now = System.currentTimeMillis();
        LOG.debug("开始获取 jsapi_ticket........");
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken.getToken() + "&type=jsapi";
        final Token ticket = new Token();
        NetWorkCenter.get(url, null, new NetWorkCenter.ResponseCallback() {
            @Override
            public void onResponse(int resultCode, String resultJson) {
                if (HttpStatus.SC_OK == resultCode) {
                    GetJsApiTicketResponse response = JSONUtil.toBean(resultJson, GetJsApiTicketResponse.class);
                    LOG.debug("获取jsapi_ticket:{}", response.getTicket());
                    if (StrUtil.isBlank(response.getTicket())) {
                        throw new WeixinException("微信公众号jsToken获取出错，错误信息:" + response.getErrcode() + "," + response.getErrmsg());
                    }
                    ticket.setToken(response.getTicket());
                }
            }
        });
        ticket.setAppid(accessToken.getAppid());
        ticket.setType(TokenType.JSAPI_TICKET);
        ticket.setUpdateTime(now);
        return ticket;
    }
}
